package com.ruanyun.modular.admin.service.impl;

import cn.stylefeng.roses.core.reqres.response.ResponseData;
import com.ruanyun.base.pojo.page.LayuiPageFactory;
import com.ruanyun.base.consts.PublicCommon;
import com.ruanyun.base.pojo.page.LayuiPageInfo;
import com.ruanyun.modular.admin.entity.TMeasures;
import com.ruanyun.modular.admin.entity.VocsEmission;
import com.ruanyun.modular.admin.mapper.TCommitReportMapper;
import com.ruanyun.modular.admin.model.result.EmissionStatisticsResult;
import com.ruanyun.modular.admin.model.result.TMeasuresResult;
import com.ruanyun.modular.admin.model.result.VocManagementLedgerResult;
import com.ruanyun.modular.admin.service.TMeasuresService;
import com.ruanyun.sys.core.shiro.ShiroKit;
import com.ruanyun.modular.admin.mapper.VocsEmissionMapper;
import com.ruanyun.modular.admin.model.params.VocsEmissionParam;
import com.ruanyun.modular.admin.model.result.VocsEmissionResult;
import  com.ruanyun.modular.admin.service.VocsEmissionService;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruanyun.sys.modular.system.entity.User;
import com.ruanyun.sys.modular.system.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * vocs排放量 服务实现类
 * </p>
 *
 * @author 
 * @since 2021-04-28
 */
@Service
public class VocsEmissionServiceImpl extends ServiceImpl<VocsEmissionMapper, VocsEmission> implements VocsEmissionService {
    @Autowired
    private TCommitReportMapper commitReportMapper;
    @Autowired
    private UserService userService;
    @Autowired
    private TMeasuresService measuresService;

    @Override
    public ResponseData add(VocsEmissionParam param){
        VocsEmission entity = getEntity(param);
        entity.setDelFlag(PublicCommon.DEL_FLAG_NORMAL);
        if(entity.getCompanyId() ==null ){
            return  ResponseData.error("未选择企业所属企业 清先查看企业信息是否填写完整");
        }
        Integer count = commitReportMapper.getIsCommit(userService.getCid());
        if(count > 0 ){
            return  ResponseData.error("该条信息已提交报告无法继续添加");
        }

        int result = this.baseMapper.insert(entity);
        if(result == 0){
            return ResponseData.error("添加失败");
        }
        return ResponseData.success();
    }

    @Override
    public void delete(VocsEmissionParam param){
        this.removeById(getKey(param));
    }

    /**
    * 删除
    *
    * @param id
    * @return
    */
    @Override
    public ResponseData updateDelFlagById(Long id) {
        VocsEmission entity = this.baseMapper.selectById(id);
        if (entity == null) {
            return ResponseData.error("该vocs排放量不存在");
        }
        entity.setDelFlag(PublicCommon.DEL_FLAG_DELETE);
        int result = this.baseMapper.updateById(entity);
        if (result == 0) {
            return ResponseData.error("删除失败");
        }
        return ResponseData.success();
    }

    @Override
    public ResponseData update(VocsEmissionParam param){
        VocsEmission oldEntity = getOldEntity(param);
        VocsEmission newEntity = getEntity(param);
        ToolUtil.copyProperties(newEntity, oldEntity);
        Integer count = commitReportMapper.getIsCommit(oldEntity.getCompanyId());
        if(count > 0 ){
            return  ResponseData.error("该条信息已提交报告无法修改");
        }
        int result = this.baseMapper.updateById(newEntity);
        if(result == 0){
        return ResponseData.error("修改失败失败");
        }
        return ResponseData.success();
    }

    @Override
    public VocsEmissionResult findBySpec(VocsEmissionParam param){
        return null;
    }

    @Override
    public List<VocsEmissionResult> findListBySpec(VocsEmissionParam param){
        return null;
    }

    @Override
    public LayuiPageInfo findPageBySpec(VocsEmissionParam param){
        /*判断当前用户是否为管理员*/
        boolean flag = ShiroKit.isAdmin();
        if (flag != true){
            User u = userService.getUserInfo();
            if("1402427539539161089".equals(u.getRoleId())){//市管理账号
                param.setIsArea("y");
            }

            if("1402427690353750018".equals(u.getRoleId()) ){ //县管理账号
                param.setCountyId(String.valueOf(u.getUserId()));
            }

            if("1162247971007717377".equals(u.getRoleId())){ //企业账号
                param.setCompanyId(userService.getCid());
            }
        }
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.customPageList1(pageContext, param);
        return LayuiPageFactory.createPageInfo(page);
    }

    private Serializable getKey(VocsEmissionParam param){
        return param.getId();
    }

    private Page getPageContext() {
        return LayuiPageFactory.defaultPage();
    }

    private VocsEmission getOldEntity(VocsEmissionParam param) {
        return this.getById(getKey(param));
    }

    private VocsEmission getEntity(VocsEmissionParam param) {
        VocsEmission entity = new VocsEmission();
        ToolUtil.copyProperties(param, entity);
        return entity;
    }
    /**
        * 启用
        *
        * @param id
        * @return
        */
    @Override
    public ResponseData enableById(Long id) {
        VocsEmission entity = this.baseMapper.selectById(id);
        if (entity == null) {
        return ResponseData.error("该vocs排放量不存在");
        }
        int result = this.baseMapper.updateById(entity);
        if (result == 0) {
            return ResponseData.error("启用失败");
        }
        return ResponseData.success();
    }

    /**
     * 禁用
     *
     * @param id
     * @return
     */
    @Override
    public ResponseData disableById(Long id) {
        VocsEmission entity = this.baseMapper.selectById(id);
        if (entity == null) {
            return ResponseData.error("该vocs排放量不存在");
        }
        int result = this.baseMapper.updateById(entity);
        if (result == 0) {
            return ResponseData.error("禁用失败");
        }
        return ResponseData.success();
    }

    @Override
    public Page<VocsEmissionResult> getVocsEmissionPage(Integer companyId,Integer emissionWay) {

        Page pageContext = getPageContext();
        Page<VocsEmissionResult>  results =  baseMapper.getVocsEmissionPage(pageContext,companyId,emissionWay);
        return results;
    }

    @Override
    public List<VocsEmissionResult> getVocsEmissionList(Integer companyId) {
        return baseMapper.getVocsEmissionList(companyId);
    }

    @Override
    public LayuiPageInfo getEmissionSummary(VocsEmissionParam param) {

        /*判断当前用户是否为管理员*/
        boolean flag = ShiroKit.isAdmin();
        if (flag != true){
            User u = userService.getUserInfo();
            if("1402427539539161089".equals(u.getRoleId())){//市管理账号
                param.setIsArea("y");
            }

            if("1402427690353750018".equals(u.getRoleId()) ){ //县管理账号
                param.setCountyId(String.valueOf(u.getUserId()));
            }

            if("1162247971007717377".equals(u.getRoleId())){ //企业账号
                param.setCompanyId(userService.getCid());
            }
        }
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.getEmissionSummary(pageContext, param);
         List<VocsEmissionResult> list = page.getRecords();
          if(list.size() != 0){
              for (VocsEmissionResult result : list) {
                  Integer companyId = result.getId();
                  VocsEmissionResult emissionResult = baseMapper.getActualEmissions(companyId);
                   if(emissionResult != null){
                       result.setActualEmissions(emissionResult.getActualEmissions());
                       result.setUnits(emissionResult.getUnits());
                   } else {
                       result.setActualEmissions(BigDecimal.valueOf(0.00));
                   }
                  TMeasuresResult measuresResult = measuresService.measureHeadInfo(companyId);
                    if(measuresResult != null){
                        result.setRemark(measuresResult.getRemark());
                        result.setEstimatedEmissions(BigDecimal.valueOf(measuresResult.getTotalMeasure()));
                    }
                     if(emissionResult != null && measuresResult!=null){
                         result.setAfterEmissions(emissionResult.getActualEmissions().subtract(BigDecimal.valueOf(measuresResult.getTotalMeasure()))  );
                     } else {
                         result.setAfterEmissions(BigDecimal.valueOf(0));
                     }
              }
          }

        return LayuiPageFactory.createPageInfo(page);
    }

    @Override
    public VocsEmissionResult getEmissionSummarys(Integer companyId) {
        VocsEmissionResult result = baseMapper.getEmissionSummarys(companyId);
        VocsEmissionResult emissionResult = baseMapper.getActualEmissions(companyId);
        if(emissionResult != null){
            result.setActualEmissions(emissionResult.getActualEmissions());
            result.setUnits(emissionResult.getUnits());
        }
        TMeasuresResult measuresResult = measuresService.measureHeadInfo(companyId);
         if(measuresResult != null){
             result.setRemark(measuresResult.getRemark());
             result.setEstimatedEmissions(BigDecimal.valueOf(measuresResult.getTotalMeasure()));
         }

        if(emissionResult != null && measuresResult!=null){
            result.setAfterEmissions(emissionResult.getActualEmissions().subtract(BigDecimal.valueOf(measuresResult.getTotalMeasure()))  );
        } else {
            result.setAfterEmissions(BigDecimal.valueOf(0));
        }
        return result;
    }

    @Override
    public ResponseData totalSummary(VocsEmissionParam param) {
        EmissionStatisticsResult results = new EmissionStatisticsResult();

        /*判断当前用户是否为管理员*/
        boolean flag = ShiroKit.isAdmin();
        if (flag != true){
            User u = userService.getUserInfo();
            if("1402427539539161089".equals(u.getRoleId())){//市管理账号
                param.setIsArea("y");
            }

            if("1402427690353750018".equals(u.getRoleId()) ){ //县管理账号
                param.setCountyId(String.valueOf(u.getUserId()));
            }

            if("1162247971007717377".equals(u.getRoleId())){ //企业账号
                param.setCompanyId(userService.getCid());
            }
        }

        List<VocsEmissionResult> list= this.baseMapper.getTotalSummary(param);
         BigDecimal totalSummary = BigDecimal.valueOf(0.00);  // 排放量估算
         BigDecimal totalActual = BigDecimal.valueOf(0.00);  //实际排放量
         BigDecimal totalAfter = BigDecimal.valueOf(0.00);   // 减排后排放量
        if(list.size() != 0){
            for (VocsEmissionResult result : list) {
                Integer companyId = result.getId();

                VocsEmissionResult emissionResult = baseMapper.getActualEmissions(companyId);
                if(emissionResult != null){
                   totalActual = totalActual.add(emissionResult.getActualEmissions());

                } else {
                    result.setActualEmissions(BigDecimal.valueOf(0.00));
                }

                TMeasuresResult measuresResult = measuresService.measureHeadInfo(companyId);
                if(measuresResult != null){
                 totalSummary = totalSummary.add(BigDecimal.valueOf(measuresResult.getTotalMeasure()));
                }

            }
             if(totalActual.compareTo(totalSummary) == 1){
                 totalAfter = totalActual.subtract(totalSummary);
             }  else {
                 totalAfter = BigDecimal.valueOf(0.00);
             }

        }
             results.setTotalActual(totalActual);
             results.setTotalSummary(totalSummary);
             results.setTotalAfter(totalAfter);
           return ResponseData.success(results);

    }

}
